/*
 * Copyright (c) 2023, LXMS (lxinet.cn).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lxinet.lxms.system.service;

import cn.lxinet.lxms.framework.core.utils.Assert;
import cn.lxinet.lxms.framework.mybatis.service.SimpleService;
import cn.lxinet.lxms.system.dto.sysRoleMenu.SysRoleMenuUpdateDto;
import cn.lxinet.lxms.system.entity.SysRole;
import cn.lxinet.lxms.system.entity.SysRoleMenu;
import cn.lxinet.lxms.system.mapper.SysRoleMenuMapper;
import cn.lxinet.lxms.system.message.SystemErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色与菜单关联
 *
 * @author zcx
 * @date 2023/07/20
 */
@Slf4j
@Service
public class SysRoleMenuService extends SimpleService<SysRoleMenu> {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;

    public List<Long> listMenuIds(Long roleId){
        SysRole sysRole = sysRoleService.findById(roleId);
        Assert.notNull(sysRole, SystemErrorCode.ROLE_NOT_EXIST);
        if (sysRole.isAdministrator()){
            //超级管理员拥有全部权限
            return sysMenuService.listAllIds();
        }else {
            return sysRoleMenuMapper.listMenuIds(roleId);
        }
    }

    /**
     * 修改
     * @param dto dto
     * @return {@link Integer}
     */
    public void update(SysRoleMenuUpdateDto dto){
        SysRole sysRole = sysRoleService.findById(dto.getRoleId());
        Assert.notNull(sysRole, SystemErrorCode.ROLE_NOT_EXIST);
        Assert.isTrue(!sysRole.isAdministrator(), SystemErrorCode.ROLE_ADMINISTRATOR_CAN_NOT_UPDATE);
        List<Long> dbMenuIds = listMenuIds(dto.getRoleId());
        List<Long> addMenuIds = new ArrayList<>(dto.getMenuIds());
        List<Long> delMenuIds = new ArrayList<>(dbMenuIds);
        addMenuIds.removeAll(dbMenuIds);
        delMenuIds.removeAll(dto.getMenuIds());
        List<SysRoleMenu> addList = new ArrayList<>();
        addMenuIds.forEach(menuId -> addList.add(new SysRoleMenu(dto.getRoleId(), menuId)));
        if (!addList.isEmpty()){
            batchInsert(addList);
        }
        if (!delMenuIds.isEmpty()){
            sysRoleMenuMapper.deleteByRoleIdAndMenuIds(dto.getRoleId(), delMenuIds);
        }
    }

}